#include "bubbleframe.h"

#include <QPainter>

const int WIDTH_SANJIAO = 8; // 三角形的宽度

BubbleFrame::BubbleFrame(ChatRole role, QWidget *parent) : QFrame(parent)
    , _role(role)
    , _margin(3)
{
    _pHLayout = new QHBoxLayout();
    // 设置文本和边界的间距
    if (_role == ChatRole::Self) {
        _pHLayout->setContentsMargins(_margin, _margin, _margin + WIDTH_SANJIAO, _margin); // 3, 3, 3 + sanjiao, 3
    }
    else{
        _pHLayout->setContentsMargins(_margin + WIDTH_SANJIAO, _margin, _margin, _margin); // 3 + sanjiao, 3, 3, 3
    }

    this->setLayout(_pHLayout);
}

void BubbleFrame::setWidget(QWidget *w)
{
    if (_pHLayout->count() > 0) {
        return ;
    }
    else {
        _pHLayout->addWidget(w);
    }
}

void BubbleFrame::paintEvent(QPaintEvent *e)
{
    QPainter painter(this);
    painter.setPen(Qt::NoPen); // 不会绘制边框线

    if (_role == ChatRole::Self) {
        QColor bk_color(158, 234, 106);
        painter.setBrush(QBrush(bk_color));

        // 画气泡
        QRect bk_rect = QRect(0, 0, this->width() - WIDTH_SANJIAO, this->height());
        painter.drawRoundedRect(bk_rect, 5, 5); // 圆角矩形
        // 画小三角
        QPointF points[3] = {
            QPointF(bk_rect.x(), 12),
            QPointF(bk_rect.x(), 10 + WIDTH_SANJIAO + 2),
            QPointF(bk_rect.x() - WIDTH_SANJIAO, 10 + WIDTH_SANJIAO - WIDTH_SANJIAO / 2)
        };
        painter.drawPolygon(points, 3); // 绘制多边形
    }
    else {
        QColor bk_color(Qt::white);
        painter.setBrush(QBrush(bk_color));

        // 画气泡
        QRect bk_rect = QRect(WIDTH_SANJIAO, 0, this->width() - WIDTH_SANJIAO, this->height());
        painter.drawRoundedRect(bk_rect, 5, 5); // 圆角矩形
        // 画小三角
        QPointF points[3] = {
            QPointF(bk_rect.x(), 12),
            QPointF(bk_rect.x(), 10 + WIDTH_SANJIAO + 2),
            QPointF(bk_rect.x() - WIDTH_SANJIAO, 10 + WIDTH_SANJIAO - WIDTH_SANJIAO / 2)
        };
        painter.drawPolygon(points, 3); // 绘制多边形
    }

    return QFrame::paintEvent(e);
}
